package com.baiyang.server.tools;


import java.io.*;

/**
 * 文件操作
 */
public class FileTool {

    /**
     * 读取文件，以字符串的形式返回
     * @param path
     * @return
     */
    public static String read(String path){
        File f = new File(path);
        if(!f.exists()){
            return null;
        }
        FileReader fr = null;
        BufferedReader br = null;
        try{
            fr = new FileReader(f);
            br = new BufferedReader(fr);
            String line;
            StringBuilder sb = new StringBuilder();
            while((line = br.readLine()) != null){
                //process the line
                sb.append(line + "\n");
            }
            return sb.toString();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            try {
                br.close();
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将str写入到本地
     * @param path
     * @param fileName
     * @param str 要写入的数据
     * @return 返回boolean，true为写入成功
     */
    public static boolean write(String path,String fileName,String str){
        File f = new File(path);
        if(!f.exists()){
            f.mkdirs();
        }
        FileOutputStream fos = null;
        try {
            File file = new File(path,fileName);
            fos = new FileOutputStream(file);
            fos.write(str.getBytes());
            fos.flush();
        }catch (Exception e){
            return false;
        }finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }
}
